package study.https.auth.https;

import org.springframework.beans.factory.annotation.Value;

import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class MyTrustManager implements X509TrustManager{
    // 相关的 jks 文件及其密码定义
    private static String TRUST_STORE;
    private static String TRUST_STORE_PASSWORD;
    X509TrustManager xtm;

    @Value("${server.ssl.trust-store}")
    public void setTrustStore(String trustStore) {
        TRUST_STORE = trustStore;
    }

    @Value("${server.ssl.trust-store-password}")
    public void setTrustStorePassword(String trustStorePassword) {
        TRUST_STORE_PASSWORD = trustStorePassword;
    }

    public MyTrustManager() throws Exception {
        // 载入 jks 文件
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(new FileInputStream(TRUST_STORE),TRUST_STORE_PASSWORD.toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509", "SunJSSE");
        tmf.init(ks);
        TrustManager[] tms = tmf.getTrustManagers();
        // 筛选出 X509 格式的信任证书
        for (int i = 0; i < tms.length; i++) {
            if (tms[i] instanceof X509TrustManager) {
                xtm = (X509TrustManager) tms[i];
                return;
            }
        }
    }
    // 服务端检验客户端证书的接口
    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        try{
            xtm.checkServerTrusted(chain, authType);
        }catch(CertificateException excep){
            System.out.println(excep.getMessage());
            throw excep;
        }
    }
    // 客户端检验服务端证书的接口
    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException{
        try{
            xtm.checkServerTrusted(chain, authType);
        }catch(CertificateException excep){
            System.out.println(excep.getMessage());
            throw excep;
        }
    }
    // 获取可接受的发行者
    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return xtm.getAcceptedIssuers();
    }
}
